﻿using Microsoft.OpenApi.Models;

namespace Zhaoxi.TakeaWay.App.Utility.SwaggerExt
{
    /// <summary>
    /// Swagger配置的扩展
    /// </summary>
    public static class CustomSwaggerExt
    {

        /// <summary>
        /// 配置Swagger注册服务扩展
        /// </summary>
        /// <param name="services"></param>
        public static void AddSwaggerExt(this IServiceCollection services)
        {
            services.AddEndpointsApiExplorer();
            services.AddSwaggerGen(option =>
            {
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    option.SwaggerDoc(version, new OpenApiInfo()
                    {
                        Title = $"朝夕教育-外卖平台Api文档--{version}版本",
                        Version = version,
                        Description = $"朝夕教育-外卖平台Api文档描述--{version}版本"
                    });
                });

                // xml文档绝对路径 
                var file = Path.Combine(AppContext.BaseDirectory, "Zhaoxi.TakeaWay.App.xml");

                // true : 显示控制器层注释
                option.IncludeXmlComments(file, true);

                // 对action的名称进行排序，如果有多个，就可以看见效果了。
                option.OrderActionsBy(o => o.RelativePath);

                //添加安全定义
                option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "请输入token,格式为 Bearer xxxxxxxx（注意中间必须有空格）",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                //添加安全要求
                option.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                  {
                        new OpenApiSecurityScheme
                        {
                            Reference =new OpenApiReference()
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id ="Bearer"
                            }
                        },
                        new string[]{ }
                    }
                });

            });
        }


        /// <summary>
        /// 配置使用Swagger
        /// </summary>
        /// <param name="app"></param>
        public static void UseSwaggerExt(this WebApplication app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(option =>
            {
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    //使用Swagger的时候, 文档生效
                    option.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"朝夕实战项目---外面平台api--{version}版本");
                });
            });
        }
    }
}
